<template>
  <el-dialog
    :title="textMap[dialogStatus]"
    :visible.sync="dialogFormVisible2"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :fullscreen="false"
  >
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="formData"
      label-position="left"
      label-width="120px"
      style="width: 500px; margin-left:50px;"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="showPasswordFlag">
        <el-input v-model="formData.password" placeholder="初始密码与用户名相同" :disabled="!selfPasswordFlag"/>
        <el-switch
          v-model="selfPasswordFlag"
          active-text="自定义密码"
          inactive-text="">
        </el-switch>
      </el-form-item>
      <el-form-item label="确认密码" prop="password2" v-if="selfPasswordFlag">
        <el-input v-model="password2" />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" />
      </el-form-item>

      <el-form-item label="关联租户" prop="tenantList">
        <el-select v-model="formData.selectedTenantIdList" multiple placeholder="选择租户" filterable class="filter-item" style="width:380px">
          <el-option v-for="item in tenantList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="关联角色" prop="roleList">
        <el-select v-model="formData.selectedRoleIdList" multiple placeholder="选择角色" filterable class="filter-item" style="width:380px">
          <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible2 = false">
        取消
      </el-button>
      <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
        确认
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import * as apiAppUser from '@/api/app_user'
import * as apiApp from '@/api/app'
import * as apiTenant from '@/api/tenant'
import * as apiRole from '@/api/role'

export default {
  name: 'CreateAppUser',
  props: ['textMap', 'dialogStatus', 'dialogFormVisible'],
  computed: {
    dialogFormVisible2: {
      get() {
        return this.dialogFormVisible
      },
      set(val) {
        // dialogFormVisible改变由父组件控制
        this.$emit('update:dialogFormVisible', val)
      }
    }
  },
  watch: {
    // 如果 `selfPasswordFlag` 发生改变，这个函数就会运行
    selfPasswordFlag: function (newVal, oldVal) {
      if (newVal === false) {
        this.formData.password = undefined
        this.password2 = undefined
      }
    }
  },
  created() {
  },
  data() {
    return {
      formData: {
        id: undefined,
        name: undefined,
        username: undefined,
        password: undefined,
        description: undefined,
        selectedTenantIdList: [],
        selectedRoleIdList: []
      },
      selfPasswordFlag: false,//指示是否需要自定义密码,默认否
      password2: undefined, //如果自定义密码,前端需要验证密码是否一致
      showPasswordFlag: true, //是否需要显示密码输入框, 编辑时需要隐藏
      tenantList: [],
      roleList: [],
      rules: {
        name: [{ required: true, message: '姓名必填', trigger: 'blur' }],
        username: [{ required: true, message: '用户名必填', trigger: 'blur' }],
        description: [{ required: true, message: '描述必填', trigger: 'blur' }]
      }
    }
  },
  methods: {
    async getTenantList() {
      const { content }=await apiTenant.getList({ // 查询列表时的参数对象
        pageNumber: 1,
        pageSize: 9999
      })
      this.tenantList = content.list
    },
    async getRoleList() {
      const { content }=await apiRole.getRoleList({ // 查询列表时的参数对象
        pageNumber: 1,
        pageSize: 500
      })
      this.roleList = content.list
    },
    clearFormData() {//清除 this.formData数据
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = undefined
      })
    },
    setCurrentRow(currentRowData) {// 修改 某条记录时 获取记录信息
      this.formData.id = currentRowData.id
      this.formData.name = currentRowData.name
      this.formData.username = currentRowData.username
      this.formData.description = currentRowData.description

      this.formData.selectedTenantIdList = []
      const tenantList = currentRowData.tenantList
      tenantList.forEach((tenant)=>{
        this.formData.selectedTenantIdList.push(tenant.id)
      })

      this.formData.selectedRoleIdList = []
      const roleList = currentRowData.roleList
      roleList.forEach((role)=>{
        this.formData.selectedRoleIdList.push(role.id)
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.selfPasswordFlag) {// 如果自定义密码,判断两次密码是否一致
            if (this.password2 !== this.formData.password) { // 密码不一致
              alert('密码不一致,请重新输入')
              return
            }
            if (this.formData.password.length < 6) {
              alert('密码长度至少为6')
              return
            }
          }

          const apiData = Object.assign({}, this.formData)
          apiData.selfPasswordFlag = this.selfPasswordFlag
          apiAppUser.createOrUpdate(apiData).then(() => {
            // 通知父组件刷新列表数据
            this.$emit('on-fresh-list')
            this.dialogFormVisible2 = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.formData)
          apiAppUser.createOrUpdate(tempData).then(() => {
            // 通知父组件刷新列表数据
            this.$emit('on-fresh-list')
            this.dialogFormVisible2 = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    clearPassword() {//编辑时无法修改密码,故需隐藏
      this.selfPasswordFlag = false
      this.formData.password = undefined
      this.password2 = undefined
      this.showPasswordFlag = false
    },
    initWhenCreate() { // 弹出创建user框时进行ui的部分必要初始化
      this.selfPasswordFlag = false
      this.formData.password = undefined
      this.password2 = undefined
      this.showPasswordFlag = true
    }
  }
}
</script>

<style scoped>

</style>
